<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>账户管理</h2>
        <p>查看和管理所有角色的账户详情信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-refresh" @click="loadAccountList">刷新</el-button>
      </div>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="用户类型">
          <el-select v-model="searchForm.userType" placeholder="选择用户类型" clearable style="width: 150px;">
            <el-option label="商家" :value="3"></el-option>
            <el-option label="区域代理" :value="2"></el-option>
            <el-option label="业务员" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" placeholder="输入用户名" clearable style="width: 200px;"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="输入手机号" clearable style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 账户列表 -->
    <el-card class="table-card" shadow="never">
      <div slot="header" class="card-header">
        <span>账户列表</span>
        <div class="header-actions">
          <el-button type="primary" size="small" icon="el-icon-view" @click="loadAccountList">刷新列表</el-button>
        </div>
      </div>

      <!-- 使用可配置表格组件 -->
      <configurable-table
        :columns="tableColumns"
        :data="filteredAccountList"
        :loading="loading"
        :show-pagination="true"
        :current-page.sync="pagination.pageIndex"
        :page-size.sync="pagination.pageSize"
        :pagination-total="pagination.total"
        @page-change="loadAccountList"
        @selection-change="handleSelectionChange"
        border
        stripe>

        <!-- 选择列 -->
        <el-table-column type="selection" width="55" align="center"></el-table-column>

        <!-- 用户名自定义显示 -->
        <template #userName="{ row }">
          <div class="user-info">
            <span class="user-name">{{ row.userName }}</span>
          </div>
        </template>

        <!-- 用户类型标签 -->
        <template #userType="{ row }">
          <el-tag :type="getUserTypeTag(row.userType)" size="small">
            {{ getUserTypeText(row.userType) }}
          </el-tag>
        </template>

        <!-- 账户余额 -->
        <template #totalBalance="{ row }">
          <span class="amount">¥{{ (row.totalBalance / 100).toFixed(2) }}</span>
        </template>

        <!-- 可提现金额 -->
        <template #balance="{ row }">
          <span class="amount withdraw-amount">¥{{ (row.balance / 100).toFixed(2) }}</span>
        </template>

        <!-- 冻结金额 -->
        <template #frozenAmount="{ row }">
          <span class="amount frozen-amount">¥{{ (row.frozenAmount / 100).toFixed(2) }}</span>
        </template>

        <!-- 操作列 -->
        <template #actions="{ row }">
          <div class="action-buttons">
            <el-button type="text" class="view-btn" @click="handleViewDetail(row)">查看详情</el-button>
            <el-button type="text" class="edit-btn" @click="handleEditAccount(row)">编辑账户</el-button>
          </div>
        </template>
      </configurable-table>
    </el-card>

    <!-- 账户详情对话框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      width="900px"
      :close-on-click-modal="false"
      custom-class="view-dialog"
      top="5vh">

      <div slot="title" class="dialog-title-wrapper">
        <i class="el-icon-user-solid"></i>
        <span>账户详情</span>
      </div>

      <div v-if="selectedAccount" class="account-detail">
        <!-- 用户头部卡片 -->
        <div class="user-header-card">
          <div class="user-avatar">
            <el-avatar
              v-if="selectedAccount.avatar"
              :src="selectedAccount.avatar"
              :size="70"
              class="avatar-image"
              @error="handleAvatarError">
              <i class="el-icon-user"></i>
            </el-avatar>
            <i v-else class="el-icon-user"></i>
          </div>
          <div class="user-basic-info">
            <div class="user-name-row">
              <h3>{{ selectedAccount.userName }}</h3>
              <el-tag :type="getUserTypeTag(selectedAccount.userType)" size="medium" effect="dark">
                {{ getUserTypeText(selectedAccount.userType) }}
              </el-tag>
            </div>
            <div class="user-meta">
              <span class="meta-item">
                <i class="el-icon-postcard"></i>
                ID: {{ selectedAccount.userId }}
              </span>
              <span class="meta-item">
                <i class="el-icon-mobile-phone"></i>
                {{ selectedAccount.phone }}
              </span>
            </div>
          </div>
        </div>

        <!-- 账户统计卡片 -->
        <el-row :gutter="15" class="stats-row">
          <el-col :span="8">
            <div class="stat-card stat-card-balance">
              <div class="stat-icon">
                <i class="el-icon-wallet"></i>
              </div>
              <div class="stat-content">
                <div class="stat-label">账户余额</div>
                <div class="stat-value">¥{{ (selectedAccount.totalBalance / 100).toFixed(2) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card stat-card-withdraw">
              <div class="stat-icon">
                <i class="el-icon-coin"></i>
              </div>
              <div class="stat-content">
                <div class="stat-label">可提现金额</div>
                <div class="stat-value">¥{{ (selectedAccount.balance / 100).toFixed(2) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card stat-card-frozen">
              <div class="stat-icon">
                <i class="el-icon-lock"></i>
              </div>
              <div class="stat-content">
                <div class="stat-label">冻结金额</div>
                <div class="stat-value">¥{{ (selectedAccount.frozenAmount / 100).toFixed(2) }}</div>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 详细信息区域 -->
        <div class="detail-info-section">
          <div class="info-card">
            <div class="info-card-header">
              <i class="el-icon-document"></i>
              <span>基本信息</span>
            </div>
            <div class="info-card-body">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">用户ID</span>
                    <span class="info-value">{{ selectedAccount.userId }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">用户名</span>
                    <span class="info-value">{{ selectedAccount.userName }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">手机号</span>
                    <span class="info-value">{{ selectedAccount.phone }}</span>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="info-item">
                    <span class="info-label">订单数量</span>
                    <span class="info-value highlight">{{ selectedAccount.orderCount || 0 }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>

          <div class="info-card">
            <div class="info-card-header">
              <i class="el-icon-tickets"></i>
              <span>交易记录</span>
            </div>
            <div class="info-card-body">
              <div class="transaction-history">
                <el-empty description="暂无交易记录" :image-size="80"></el-empty>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button size="medium" @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" size="medium" icon="el-icon-edit" @click="handleEditAccount(selectedAccount)">编辑账户</el-button>
      </div>
    </el-dialog>

    <!-- 编辑账户对话框 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      custom-class="action-dialog"
      top="10vh">

      <div slot="title" class="dialog-title-wrapper">
        <i class="el-icon-edit"></i>
        <span>编辑账户</span>
      </div>

      <!-- 账户概览 -->
      <div v-if="selectedAccount" class="edit-account-overview">
        <div class="overview-item">
          <i class="el-icon-user"></i>
          <span class="overview-label">用户名：</span>
          <span class="overview-value">{{ selectedAccount.userName }}</span>
        </div>
        <div class="overview-item">
          <i class="el-icon-postcard"></i>
          <span class="overview-label">用户ID：</span>
          <span class="overview-value">{{ selectedAccount.userId }}</span>
        </div>
      </div>

      <el-divider></el-divider>

      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="120px" class="edit-form">
        <el-alert
          title="温馨提示"
          type="info"
          description="修改账户金额将会影响用户的可用余额，请谨慎操作！"
          :closable="false"
          show-icon
          class="form-alert">
        </el-alert>

        <el-form-item label="可提现金额" prop="balance">
          <el-input-number
            v-model="editForm.balance"
            :precision="2"
            :step="100"
            :min="0"
            controls-position="right"
            placeholder="请输入可提现金额"
            class="custom-input-number">
            <template slot="prefix">¥</template>
          </el-input-number>
          <div class="form-item-tip">
            <i class="el-icon-info"></i>
            <span>当前金额: ¥{{ selectedAccount ? (selectedAccount.balance / 100).toFixed(2) : '0.00' }}</span>
          </div>
        </el-form-item>

        <el-form-item label="冻结金额" prop="frozenAmount">
          <el-input-number
            v-model="editForm.frozenAmount"
            :precision="2"
            :step="100"
            :min="0"
            controls-position="right"
            placeholder="请输入冻结金额"
            class="custom-input-number">
            <template slot="prefix">¥</template>
          </el-input-number>
          <div class="form-item-tip">
            <i class="el-icon-info"></i>
            <span>当前金额: ¥{{ selectedAccount ? (selectedAccount.frozenAmount / 100).toFixed(2) : '0.00' }}</span>
          </div>
        </el-form-item>

        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="editForm.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入修改备注说明，便于后续追溯"
            maxlength="200"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer edit-footer">
        <el-button size="medium" @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" size="medium" icon="el-icon-check" @click="submitEditForm" :loading="editLoading">
          {{ editLoading ? '保存中...' : '确认修改' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccountList, getAccountInfo } from '@/api/aggregation'

export default {
  name: 'AccountManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        userType: '',
        userName: '',
        phone: ''
      },
      accountList: [],
      filteredAccountList: [],
      selectedAccounts: [],
      // 表格列配置
      tableColumns: [
        { prop: 'userId', label: '用户ID', width: 80, align: 'center' },
        { prop: 'userName', label: '用户名', minWidth: 120, slot: 'userName' },
        { prop: 'userType', label: '用户类型', width: 100, align: 'center', slot: 'userType' },
        { prop: 'phone', label: '手机号', minWidth: 140, align: 'center' },
        { prop: 'totalBalance', label: '账户余额', minWidth: 120, align: 'center', sortable: true, slot: 'totalBalance' },
        { prop: 'balance', label: '可提现金额', minWidth: 130, align: 'center', sortable: true, slot: 'balance' },
        { prop: 'frozenAmount', label: '冻结金额', minWidth: 120, align: 'center', slot: 'frozenAmount' },
        { prop: 'orderCount', label: '订单数量', width: 100, align: 'center', sortable: true },
        {
          prop: 'lastUpdateTime',
          label: '最后更新',
          minWidth: 160,
          align: 'center',
          formatter: (row) => this.formatDateTime(row.lastUpdateTime)
        },
        { label: '操作', minWidth: 200, align: 'center', fixed: 'right', slot: 'actions' }
      ],
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      detailDialogVisible: false,
      editDialogVisible: false,
      selectedAccount: null,
      editForm: {
        userId: '',
        balance: 0,
        frozenAmount: 0,
        remark: ''
      },
      editRules: {
        balance: [
          { required: true, message: '请输入可提现金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额不能小于0', trigger: 'blur' }
        ],
        frozenAmount: [
          { required: true, message: '请输入冻结金额', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额不能小于0', trigger: 'blur' }
        ]
      },
      editLoading: false
    }
  },
  created() {
    this.loadAccountList()
  },
  methods: {
    // 加载账户列表
    async loadAccountList() {
      try {
        this.loading = true
        const params = {
          pageIndex: this.pagination.pageIndex,
          pageSize: this.pagination.pageSize,
          ...this.searchForm
        }

        const response = await getAccountList(params)
        if (response.code === 0) {
          this.accountList = response.data.list || []
          this.pagination.total = response.data.total || 0
          this.filteredAccountList = [...this.accountList]
          Logger.log('账户列表加载成功:', this.accountList)
        } else {
          this.$message.error(response.msg || '加载账户列表失败')
        }
      } catch (error) {
        Logger.error('加载账户列表失败:', error)
        this.$message.error('加载账户列表失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.pageIndex = 1
      this.loadAccountList()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        userType: '',
        userName: '',
        phone: ''
      }
      this.pagination.pageIndex = 1
      this.loadAccountList()
    },

    // 选择改变
    handleSelectionChange(selection) {
      this.selectedAccounts = selection
    },

    // 查看详情
    handleViewDetail(row) {
      this.selectedAccount = row
      this.detailDialogVisible = true
    },

    // 编辑账户
    handleEditAccount(row) {
      this.selectedAccount = row
      this.editForm = {
        userId: row.userId,
        balance: row.balance / 100, // 转换为元
        frozenAmount: row.frozenAmount / 100, // 转换为元
        remark: ''
      }
      this.editDialogVisible = true
    },

    // 提交编辑表单
    async submitEditForm() {
      try {
        await this.$refs.editForm.validate()
        this.editLoading = true

        // 这里应该调用更新账户的API
        // const response = await updateAccount(this.editForm)

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        this.$message.success('账户更新成功')
        this.editDialogVisible = false
        this.loadAccountList()
      } catch (error) {
        Logger.error('更新账户失败:', error)
        this.$message.error('更新账户失败')
      } finally {
        this.editLoading = false
      }
    },

    // 处理头像加载失败
    handleAvatarError() {
      // 头像加载失败时，el-avatar会自动显示fallback内容（即el-icon-user图标）
      console.log('头像加载失败，显示默认图标')
    },


    // 获取用户类型标签
    getUserTypeTag(userType) {
      const typeMap = {
        2: 'warning',  // 区域代理
        3: 'success',  // 商家
        4: 'info'      // 业务员
      }
      return typeMap[userType] || 'default'
    },

    // 获取用户类型文本
    getUserTypeText(userType) {
      const typeMap = {
        2: '区域代理',
        3: '商家',
        4: '业务员'
      }
      return typeMap[userType] || '未知'
    },

    // 格式化时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.header-left h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-left p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.amount {
  font-weight: 600;
  color: #67c23a;
}

.withdraw-amount {
  color: #e6a23c;
}

.frozen-amount {
  color: #f56c6c;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.view-btn {
  color: #409eff;
}

.edit-btn {
  color: #e6a23c;
}

/* ==================== 对话框标题样式 ==================== */
.dialog-title-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.dialog-title-wrapper i {
  font-size: 20px;
  color: #409eff;
}

/* ==================== 账户详情弹框样式 ==================== */
.account-detail {
  padding: 0;
}

/* 用户头部卡片 */
.user-header-card {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.user-avatar {
  width: 70px;
  height: 70px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  border: 3px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

.user-avatar .avatar-image {
  border: none;
  background: transparent;
}

.user-avatar i {
  font-size: 36px;
  color: white;
}

.user-basic-info {
  flex: 1;
  color: white;
}

.user-name-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
}

.user-name-row h3 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: white;
}

.user-meta {
  display: flex;
  gap: 20px;
  opacity: 0.95;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
}

.meta-item i {
  font-size: 16px;
}

/* 统计卡片 */
.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  border-radius: 10px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.stat-card-balance {
  border-left: 4px solid #67c23a;
}

.stat-card-withdraw {
  border-left: 4px solid #e6a23c;
}

.stat-card-frozen {
  border-left: 4px solid #f56c6c;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-card-balance .stat-icon {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  color: white;
}

.stat-card-withdraw .stat-icon {
  background: linear-gradient(135deg, #e6a23c 0%, #f0c878 100%);
  color: white;
}

.stat-card-frozen .stat-icon {
  background: linear-gradient(135deg, #f56c6c 0%, #f89898 100%);
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 6px;
}

.stat-value {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

/* 详细信息区域 */
.detail-info-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.info-card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.info-card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 20px;
  background: linear-gradient(to right, #f5f7fa, #ffffff);
  border-bottom: 1px solid #ebeef5;
  font-weight: 600;
  color: #303133;
}

.info-card-header i {
  font-size: 18px;
  color: #409eff;
}

.info-card-body {
  padding: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f2f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  width: 100px;
  color: #909399;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.info-value.highlight {
  color: #409eff;
  font-weight: 600;
}

.transaction-history {
  min-height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* ==================== 编辑账户弹框样式 ==================== */
.edit-account-overview {
  display: flex;
  gap: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8eaf0 100%);
  border-radius: 8px;
  margin-bottom: 10px;
}

.overview-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.overview-item i {
  font-size: 16px;
  color: #409eff;
}

.overview-label {
  font-weight: 500;
}

.overview-value {
  color: #303133;
  font-weight: 600;
}

.edit-form {
  padding: 10px 0;
}

.form-alert {
  margin-bottom: 24px;
}

.custom-input-number {
  width: 100%;
}

.form-item-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border-left: 3px solid #409eff;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
}

.form-item-tip i {
  color: #409eff;
  font-size: 14px;
}

/* ==================== 对话框底部按钮 ==================== */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
}

.edit-footer {
  padding-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  /* 弹框响应式 */
  .user-header-card {
    flex-direction: column;
    text-align: center;
  }

  .user-meta {
    flex-direction: column;
    gap: 10px;
  }

  .stat-card {
    flex-direction: column;
    text-align: center;
  }

  .edit-account-overview {
    flex-direction: column;
    gap: 15px;
  }
}
</style>
